import request from './request'

export function login(username, password){
  console.log('process.env.VITE_API_ROOT', process.env.VITE_API_ROOT)
  localStorage.removeItem('token')
	return request({
		url:'/user/users/login/',
		method:"post",
    data: {
      username,
      password
    }
	})
}

export function updateUserInfo(id, data) {
	return request({
		url:`/user/users/${id}/`,
		method:"patch",
    data
	})
}

export function addUser(data) {
	return request({
		url:'/user/users/',
		method:"post",
    data
	})
}

export function logout() {
	return request({
		url:'/user/users/logout/',
		method:"post"
	})
}

export function loadGroups() {
	return request({
		url:'/user/groups/',
		method:"get"
	})
}

export function listUsers(params) {
	return request({
		url:'/user/users/',
		method:"get",
    params
	})
}

export function deleteUsers(ids) {
	return request({
		url:'/user/users/delete_many/',
		method:"post",
    data: {user_ids: ids}
	})
}

export function getResearchers() {
	return request({
		url:'/user/users/?by_groupname=研究员',
		method:"get"
	})
}

// 以下是本地调用

export function setUserCredit(resData) {
	localStorage.setItem('token', resData['token'])
	localStorage.setItem('user_info', JSON.stringify(resData['user_info']))
}

export function resetMyUserInfo(data) {
	localStorage.setItem('user_info', JSON.stringify(data))
}

export function clearToken() {
  localStorage.removeItem('token')
	localStorage.removeItem('user_info')
}

export function myUserInfo() {
	return JSON.parse(localStorage.getItem('user_info'))
}

export function getUserName() {
	return myUserInfo().username
}

export function getUserGroupsString() {
	return myUserInfo().groups.map(v=>v.name).join(',')
}

export function isAdmin() {
	const groups = getUserGroupsString()
	if (groups) {
		 return new Set(groups.split(',')).has('管理员')
	}	
	return false
}

export function isResearcher() {
	const groups = getUserGroupsString()
	if (groups) {
		 return new Set(groups.split(',')).has('研究员')
	}	
	return false
}

export function isStudent() {
	const groups = getUserGroupsString()
	if (groups) {
		 return new Set(groups.split(',')).has('学生')
	}	
	return false
} 

export function isLoggedIn() {
  return !!localStorage.getItem('token')
}
